<template>
    <div class="code-picker">
      <el-form-item label="签到码" prop="code">
        <el-input
          v-model="code"
          placeholder="请输入或生成4位数字"
          maxlength="4"
          show-word-limit
          style="width: 200px"
        >
          <template #append>
            <el-button @click="generateCode">生成</el-button>
          </template>
        </el-input>
      </el-form-item>
    </div>
  </template>
  
  <script setup>
  import { reactive, ref, defineExpose, defineEmits } from 'vue'
  import { ElMessage } from 'element-plus'
  import axios from 'axios';
  const API_BASE = 'http://localhost:8081/session'
const api = {
  create: `${API_BASE}/addCode`,
}
  const codeData = reactive({
  sessionType: '签到码',
  patternCode: ''
})
  // 通过v-model实现双向绑定
  const emit = defineEmits(['update:modelValue'])
  const code = ref('')
  
  // 生成随机4位数字签到码
  const generateCode = () => {
    code.value = String(Math.floor(1000 + Math.random() * 9000))
    emit('update:modelValue', code.value) // 同步到父组件
  }
  
  // 验证方法（供父组件调用）
  const validate = () => {
    if (!code.value) {
      ElMessage.warning('请生成或输入签到码')
      return false
    }
    if (!/^\d{4}$/.test(code.value)) {
      ElMessage.error('签到码必须为4位数字')
      return false
    }
    return true
  }
  const handleCreate = async () => {
    codeData.patternCode = code.value;
    // 构造请求数据
    const payload = {
      sessionType: codeData.sessionType,
      patternCode: codeData.patternCode
    };
    console.log(payload)
    // 发送请求
    const response = await axios.post(api.create, payload);
    return response.data;
};
  defineExpose({
    codeData,
    code,
    validate,
    handleCreate
  })
  </script>
  
  <style scoped>
  .code-picker {
    padding: 20px;
    border: 1px solid #eee;
    border-radius: 4px;
    background: #f5f7fa;
  }
  
  .el-input-group__append {
    background: #409eff;
    color: white;
    border: none;
  }
  
  .el-input-group__append:hover {
    background: #66b1ff;
  }
  </style>